<template>
  <div class="search-result">
    <form action="/">
      <van-search
        v-model="keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <!-- 只有商品数据才显示 -->
    <van-dropdown-menu v-if="searchData.length">
      <van-dropdown-item @change="change" v-model="sort" :options="option" />
    </van-dropdown-menu>
    <!-- 搜索结果页面 -->
    <div class="goodslist">
      <Goods
        v-for="item in searchData"
        :key="item.id"
        :data="item"
        @click="clickHandle"
      ></Goods>
    </div>
    <van-empty v-if="!searchData.length" description="暂无搜索结果" />
  </div>
</template>

<script>
// 导入商品组件
import Goods from "@/components/Goods.vue";
import { fetchSeekGoods } from "@/api/index";
export default {
  data() {
    return {
      keyword: this.$route.params.keyword,
      page: 1,
      pagesize: 10,
      searchData: [],
      sort: "buy",
      order: "desc",
      option: [
        { text: "销量", value: "buy" },
        { text: "好评", value: "likes" },
        { text: "价格", value: "sell_price" },
      ],
    };
  },
  created() {
    this._fetchSearchData();
  },
  methods: {
    async _fetchSearchData() {
      // 2. 发送ajax，做关键字匹配
      let data = {
        value: this.keyword,
        //  排序字段
        sort: this.sort,
        //  降序desc
        order: this.order,
        page: this.page,
        pagesize: this.pagesize,
      };
      let result = await fetchSeekGoods(data);
      this.searchData = result;
    },
    onCancel() {
      this.$router.back();
    },
    clickHandle(item) {
      this.$router.push("/goodsdetail/" + item.id);
    },
    change(value) {
      // 更改排序字段
      this.sort = value;
      // 在发送请求即可
      this.searchData = [];
      this._fetchSearchData();
    },
    onSearch() {
      this._fetchSearchData();
    },
  },
  components: {
    Goods,
  },
};
</script>

<style lang="scss" scoped>
.search-result {
  .goodslist {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    background: #f0eded;
    padding-top: 10px;
  }
}
</style>
